﻿using System;
using System.Collections.Generic;

using Microsoft.WindowsAzure.StorageClient;

namespace BizTalkFactory.Adapters.AzureStorage
{
    sealed class QueueStorageEventArgs : StorageEventArgs
    {
        public CloudQueueMessage Message;

        public QueueStorageEventArgs(string queueName, CloudQueueMessage message)
            : base(queueName)
        {
            Message = message;
        }
    }

    class QueueStorageListener : StorageListener
    {
        private List<String> queueNames_ = new List<String>();

        public QueueStorageListener(AzureStorageAdapterConnection connection)
            : base(connection)
        {
        }

        #region Attributes

        public IList<String> QueueNames
        {
            get { return queueNames_; }
        }

        #endregion

        #region Overrides

        protected override void StartingListener()
        {
            base.StartingListener();
        }

        protected override void Listening()
        {
            foreach (String queueName in queueNames_)
            {
                // Peek specified Azure Storage Queue

                CloudQueue queue = Connection.QueueStorage.GetQueueReference(queueName);
                if (queue.PeekMessage() == null)
                    continue;

                // Extract as many messages as possible from Queue

                while (true)
                {
                    CloudQueueMessage message = queue.GetMessage(TimeSpan.FromSeconds(PollingIntervalInSeconds));
                    if (message == null)
                        break;

                    QueueStorageEventArgs e = new QueueStorageEventArgs(queueName, message);

                    RaiseReceivedEvent(this, e);

                    // Delete message from Queue

                    if (!e.Cancel)
                        queue.DeleteMessage(message);
                }
            }

            base.Listening();
        }

        protected override void StoppingListener()
        {
            base.StoppingListener();
        }

        #endregion
    }
}
